<?php

namespace app\company\controller;

use app\admin\model\GoodsRule;
use app\company\model\Goods;
use app\company\validate\PickingGoodsValidate;
use app\service\traits\Crud;
use app\company\model\PickingGoods as PickingGoodsModel;
use \app\company\model\WarehouseStorageGoodsLogs;
use app\company\model\WarehouseStorage;


class PickingGoods extends Base
{
    private PickingGoodsModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new PickingGoodsModel();
        $this->validateClass = PickingGoodsValidate::class;
        $this->isGs          = true;
        $this->withSearch    = 'id,name,create_time';
        $this->append        = 'is_dow_text,is_print_text';
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->dow_time   = setDates($item->dow_time);
            $item->print_time = setDates($item->print_time);
            $item->pick_time  = setDates($item->pick_time);
        });
    }

    public function detailFormat($info): mixed
    {
        //商品,规格,条码,数量,库位,生产日期
        $field            = "goods_rule_id,max(goods_id) goods_id,company_id,warehouse_storage_id,production_time,sum(quantity) quantity";
        $group            = 'goods_rule_id,warehouse_storage_id,production_time';
        $date             = date('Y-m-d', strtotime("-1 day", $info->pick_time));
        $info->detail     = WarehouseStorageGoodsLogs::gs($this->company_id)->type(2)->field("goods_id")->whereDay("create_time", $date)->group("goods_id")->select()->each(function ($item) use ($field, $group, $date) {
            $item->goods  = Goods::where('id', $item->goods_id)->withTrashed()->field('id,name,no')->find();
            $item->detail = WarehouseStorageGoodsLogs::gs($this->company_id)->type(2)->goodsId($item->goods_id)->whereDay("create_time", $date)->field($field)->group($group)->select()->each(function ($detail) {
                $detail->goods_rule             = GoodsRule::where('id', $detail->goods_rule_id)->withTrashed()->field('id,spec_name,sku')->find();
                $detail->warehouse_storage_name = WarehouseStorage::where('id', $detail->warehouse_storage_id)->withTrashed()->value('name');
                $detail->production_time        = setDates($detail->production_time);
            });
        });
        $info->dow_time   = setDates($info->dow_time);
        $info->print_time = setDates($info->print_time);
        $info->pick_time  = setDates($info->pick_time);
        return $info;
    }
}